package com.handle;

import com.constant.ServiceConstant;
import com.message.rpc.RpcRequestMessage;
import com.message.rpc.RpcResponseMessage;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Method;
import java.util.Objects;
import java.util.Optional;

/**
 * @author linyu.dai
 * @project rpc
 * @description 处理远程调用请求
 * @creat 2022/11/27 22:17:01
 */
@Slf4j
public class RpcRequestHandle extends SimpleChannelInboundHandler<RpcRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcRequestMessage msg) throws Exception {
        log.info("request message{}", msg);
        RpcResponseMessage rpcResponseMessage = new RpcResponseMessage();
        rpcResponseMessage.setMessageId(msg.getMessageId());
        try {
            Class<?> aClass = ServiceConstant.getClassPath(msg.getServiceName());
            Method method = aClass.getMethod(msg.getMethodName(), msg.getParameterTypes());
            //获取实例
            Object o = aClass.getDeclaredConstructor().newInstance();
            Object invoke = method.invoke(o, msg.getParameterValue());
            if(msg.getReturnType().isInstance(invoke)){
                rpcResponseMessage.setReturnValue(invoke);
                ctx.channel().writeAndFlush(rpcResponseMessage);
                log.info("response message:{}", rpcResponseMessage);
            }else{
                throw new RuntimeException("返回值异常....");
            }
        }catch (Exception e){
            //返回异常值
            e.printStackTrace();
            rpcResponseMessage.setExceptionValue(new Exception("rpc调用出错:"+e.getCause().getMessage()));
            ctx.channel().writeAndFlush(rpcResponseMessage);
            log.info("response error message:{}", rpcResponseMessage);
        }
    }

}
